package com.cyq.dascma.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * md5工具类，把字符串通过md5摘要加密后以字符串返回
 * dingwen
 * 2019/12/2 17:35
 **/
public class Md5Util {
    /**
     * 对str使用md5进行摘要加密并且返回
     * @return java.lang.String
     */
    public static String createMd5String(String str){
        char[] hexs = {'0','1','2','3','4','5','6','7','8','9','a','b','c','b','e','f'};
        //1.把指定字符串转化成字节数组
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        //2.使用MD5摘要算法获取MessageDigest对象
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            //3.更新摘要
            messageDigest.update(bytes);
            //4.获取密文字节
            byte[] digest = messageDigest.digest();
            //5.转成十六进制的字符串
            int j = digest.length;
            char[] arr = new char[j*2];
            for (int i = 0;i < j;i++ ){
                byte b = digest[i];
                //按位与会先把数字变成二进制，最后返回十进制
                int a = b>>>4 & 0xf;
                int c = b & 0xf;
                arr[2*i] = hexs[a];
                arr[2*i+1] = hexs[c];
            }
            return new String(arr);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
